package main

import (
	"fmt"
	"github.com/biocrosscoder/flex/typed/collections"
	"math/rand"
)

type History interface {
	Open(page string) (ok bool)
	Forward() (ok bool, page string)
	Back() (ok bool, page string)
}

type history struct {
	stack1 collections.Stack[string]
	stack2 collections.Stack[string]
}

func (h *history) Open(page string) (ok bool) {
	return h.stack1.Push(page)
}

func (h *history) Forward() (ok bool, page string) {
	if h.stack2.Empty() || h.stack1.Full() {
		return
	}
	page, ok = h.stack2.Pop()
	_ = h.stack1.Push(page)
	return
}

func (h *history) Back() (ok bool, page string) {
	if h.stack1.Empty() || h.stack2.Full() {
		return
	}
	page, _ = h.stack1.Pop()
	_ = h.stack2.Push(page)
	page, ok = h.stack1.Peek()
	if !ok {
		h.Forward()
	}
	return
}

var ho History

func init() {
	ho = &history{
		stack1: collections.NewStack[string](10),
		stack2: collections.NewStack[string](10),
	}
}

func main() {
	openRandomPage()
	tryBack()
	openRandomPage()
	tryForward()
	tryBack()
	tryForward()
}

func tryForward() {
	ok, page := ho.Forward()
	if ok {
		fmt.Printf("前进成功，当前页面为: %s\n", page)
	} else {
		fmt.Println("前进失败，已在最新页面")
	}
}

func tryBack() {
	ok, page := ho.Back()
	if ok {
		fmt.Printf("回退成功，当前页面为: %s\n", page)
	} else {
		fmt.Println("回退失败，历史记录为空")
	}
}

func openRandomPage() {
	pages := []string{"首页", "关于我们", "产品", "服务", "联系我们", "博客", "资源", "支持"}
	page := pages[rand.Intn(len(pages))]
	if ho.Open(page) {
		fmt.Printf("打开成功，当前页面为：%s\n", page)
	} else {
		fmt.Println("打开失败，历史记录已满")
	}
}
